package cn.px.crm.customerbusiness.controller;

import cn.px.common.annotation.Log;
import cn.px.common.core.controller.BaseController;
import cn.px.common.core.domain.AjaxResult;
import cn.px.common.core.page.TableDataInfo;
import cn.px.common.enums.BusinessType;
import cn.px.common.utils.poi.ExcelUtil;
import cn.px.crm.customer.domain.CrmCustomer;
import cn.px.crm.customer.service.ICrmCustomerService;
import cn.px.crm.customerbusiness.domain.CrmCustomerBusiness;
import cn.px.crm.customerbusiness.service.ICrmCustomerBusinessService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户业务管理Controller
 *
 * @author ruoyi
 * @date 2022-07-16
 */
@RestController
@RequestMapping("/customerbusiness/customerbusiness")
public class CrmCustomerBusinessController extends BaseController
{
    @Autowired
    private ICrmCustomerBusinessService crmCustomerBusinessService;

    @Autowired
    private ICrmCustomerService customerService;

    /**
     * 查询客户业务管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CrmCustomerBusiness crmCustomerBusiness)
    {
        startPage();
        List<CrmCustomerBusiness> list = crmCustomerBusinessService.selectCrmCustomerBusinessList(crmCustomerBusiness);
        return getDataTable(list);
    }


    @GetMapping("/lists")
    public TableDataInfo lists(CrmCustomerBusiness crmCustomerBusiness)
    {
        startPage();
        List<CrmCustomerBusiness> list = crmCustomerBusinessService.selectCustomerBusinessLists(crmCustomerBusiness);
        return getDataTable(list);
    }

    /**
     * 导出客户业务管理列表
     */
    @Log(title = "客户业务管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmCustomerBusiness crmCustomerBusiness)
    {
        List<CrmCustomerBusiness> list = crmCustomerBusinessService.selectCrmCustomerExportList(crmCustomerBusiness);

        if(CollectionUtils.isNotEmpty(list)){
            Map<Long,List<CrmCustomerBusiness>> map = new HashMap<>();
            for(int i=0;i<list.size();i++){
                List<CrmCustomerBusiness> itemList = new ArrayList();
                List<CrmCustomerBusiness> itemsList = new ArrayList();
                CrmCustomerBusiness cbs = new CrmCustomerBusiness();
                CrmCustomerBusiness customerBusiness = list.get(i);
                CrmCustomer crmCustomer = customerBusiness.getCrmCustomer();
                Long pid = crmCustomer.getPid();
                Long cid = customerBusiness.getCid();
                cbs.setCid(crmCustomer.getPid());
                cbs.setAddTime(customerBusiness.getAddTime());
                List<CrmCustomerBusiness> customerBusinesses = crmCustomerBusinessService.selectCrmCustomerBusinessList(cbs);
                if(CollectionUtils.isEmpty(customerBusinesses)){
                    for(int j=0;j<list.size();j++){
                        CrmCustomerBusiness business = list.get(j);
                        CrmCustomer customer = business.getCrmCustomer();
                        if("3".equals(customer.getType()) && pid.longValue()==customer.getPid().longValue()
                                && cid.longValue()!=business.getCid().longValue()
                                && customerBusiness.getBusinessId().longValue()==business.getBusinessId().longValue()){
                            //各项指标一致的数据放在一起
                            itemList.add(customerBusiness);
                            itemList.add(business);
                        }else if("3".equals(customer.getType()) && pid.longValue()==customer.getPid().longValue()
                                && cid.longValue()!=business.getCid().longValue()
                                && customerBusiness.getBusinessId().longValue()!=business.getBusinessId().longValue()){
                            //各项指标不一致的放在一起
                            //itemList.add(customerBusiness);
                            itemsList.add(business);
                        }
                    }
                    if(CollectionUtils.isNotEmpty(itemList)){
                        map.put(customerBusiness.getBusinessId(),itemList);
                    }
                    if(CollectionUtils.isNotEmpty(itemsList)){
                        map.put(customerBusiness.getBusinessId(),itemsList);
                    }
                }
            }
            if(map.size()>0){
                for(Map.Entry<Long,List<CrmCustomerBusiness>> entry : map.entrySet()){
                    List<CrmCustomerBusiness> value = entry.getValue();
                    CrmCustomerBusiness cb = new CrmCustomerBusiness();
                    if(value.size()>0){
                        CrmCustomer crmCustomer = value.get(0).getCrmCustomer();
                        CrmCustomer parentCustomer = customerService.selectCrmCustomerById(crmCustomer.getPid());
                        Long peopleNum = 0L;
                        Long preNum = 0L;
                        if(CollectionUtils.isNotEmpty(value)){
                            for(CrmCustomerBusiness business : value){
                                peopleNum += business.getPeopleNum();
                                preNum += business.getPreMonthNum();
                            }
                            cb.setPeopleNum(peopleNum);
                            cb.setPreMonthNum(preNum);
                            cb.setCrmCustomer(parentCustomer);
                            cb.setCname(parentCustomer.getName());
                            cb.setAddTime(value.get(0).getAddTime());
                            cb.setBusinessName(value.get(0).getBusinessName());
                            cb.setSalerName(value.get(0).getSalerName());
                            cb.setSubNum(peopleNum-preNum);
                            if(preNum.longValue()>0){
                                int round = Math.round((peopleNum - preNum) / preNum * 100);
                                cb.setDivNum(round+"%");
                            }else{
                                cb.setDivNum("0%");
                            }
                        }
                        list.add(cb);
                    }

                }
            }

//            CrmCustomerBusiness cb = new CrmCustomerBusiness();
//                for(int i=0;i<list.size();i++){
//                    CrmCustomerBusiness customerBusiness = list.get(i);
//                    CrmCustomer crmCustomer = customerBusiness.getCrmCustomer();
//                    if("3".equals(crmCustomer.getType())){
//                        Long pid = crmCustomer.getPid();
//                        Long cid = customerBusiness.getCid();
//                        Long peopleNum = customerBusiness.getPeopleNum();
//                        Long preNum = customerBusiness.getPreMonthNum();
//                        CrmCustomer parentCustomer = customerService.selectCrmCustomerById(crmCustomer.getPid());
//                        //需要判断下当月有没有此集团的数据，如果有的话就不管 如果没有执行以下逻辑
//                        CrmCustomerBusiness cbs = new CrmCustomerBusiness();
//                        cbs.setCid(crmCustomer.getPid());
//                        cbs.setAddTime(customerBusiness.getAddTime());
//                        List<CrmCustomerBusiness> customerBusinesses = crmCustomerBusinessService.selectCrmCustomerBusinessList(cbs);
//                        if(CollectionUtils.isEmpty(customerBusinesses)){
//                            for(int j=0;j<list.size();j++){
//                                CrmCustomerBusiness business = list.get(j);
//                                CrmCustomer customer = business.getCrmCustomer();
//                                if("3".equals(customer.getType()) && pid.longValue()==customer.getPid().longValue()
//                                        && cid.longValue()!=business.getCid().longValue()
//                                        && customerBusiness.getBusinessId().longValue()==business.getBusinessId().longValue()){
//                                    peopleNum += business.getPeopleNum();
//                                    preNum += business.getPreMonthNum();
//                                }else if("3".equals(customer.getType()) && pid.longValue()==customer.getPid().longValue()
//                                        && cid.longValue()!=business.getCid().longValue()
//                                        && customerBusiness.getBusinessId().longValue()!=business.getBusinessId().longValue()){
//                                    CrmCustomerBusiness ccb = new CrmCustomerBusiness();
//                                    ccb.setCrmCustomer(parentCustomer);
//                                    ccb.setCname(parentCustomer.getName());
//                                    ccb.setAddTime(customerBusiness.getAddTime());
//                                    ccb.setPeopleNum(peopleNum);
//                                    ccb.setPreMonthNum(preNum);
//                                    ccb.setSubNum(peopleNum-preNum);
//                                    if(preNum.longValue()>0){
//                                        int round = Math.round((peopleNum - preNum) / preNum * 100);
//                                        ccb.setDivNum(round+"%");
//                                    }else{
//                                        ccb.setDivNum("0%");
//                                    }
//                                    list.add(ccb);
//                                }
//                            }
//                            cb.setCrmCustomer(parentCustomer);
//                            cb.setCname(parentCustomer.getName());
//                            cb.setAddTime(customerBusiness.getAddTime());
//                            cb.setPeopleNum(peopleNum);
//                            cb.setBusinessName(customerBusiness.getBusinessName());
//                            cb.setSalerName(customerBusiness.getSalerName());
//                            cb.setPreMonthNum(preNum);
//                            cb.setSubNum(peopleNum-preNum);
//                            if(preNum.longValue()>0){
//                                int round = Math.round((peopleNum - preNum) / preNum * 100);
//                                cb.setDivNum(round+"%");
//                            }else{
//                                cb.setDivNum("0%");
//                            }
//                        }
//                    }
//                }
//            list.add(cb);
        }
        List<CrmCustomerBusiness> collect = list.stream().sorted(Comparator.comparing(CrmCustomerBusiness::getCname)).collect(Collectors.toList());
        ExcelUtil<CrmCustomerBusiness> util = new ExcelUtil<CrmCustomerBusiness>(CrmCustomerBusiness.class);
        util.exportExcel(response, collect, "客户业务管理数据");
    }

    /**
     * 获取客户业务管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(crmCustomerBusinessService.selectCrmCustomerBusinessById(id));
    }

    /**
     * 新增客户业务管理
     */
    @Log(title = "客户业务管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmCustomerBusiness crmCustomerBusiness)
    {
        return toAjax(crmCustomerBusinessService.insertCrmCustomerBusiness(crmCustomerBusiness));
    }

    /**
     * 修改客户业务管理
     */
    @Log(title = "客户业务管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmCustomerBusiness crmCustomerBusiness)
    {
        return toAjax(crmCustomerBusinessService.updateCrmCustomerBusiness(crmCustomerBusiness));
    }

    /**
     * 删除客户业务管理
     */
    @Log(title = "客户业务管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(crmCustomerBusinessService.deleteCrmCustomerBusinessByIds(ids));
    }

    @Log(title = "客户业务管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delCustomerbusinesses/{ids}")
    public AjaxResult delCustomerbusinesses(@PathVariable Long[] ids){
        List<CrmCustomerBusiness> customerBusinessLists = new ArrayList<>();
        if(ids.length>0){
            List<CrmCustomerBusiness> customerBusinesses = new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                CrmCustomerBusiness business = crmCustomerBusinessService.selectCrmCustomerBusinessById(ids[i]);
                customerBusinesses.add(business);
            }
            if(CollectionUtils.isNotEmpty(customerBusinesses)){
                for(CrmCustomerBusiness customerBusiness : customerBusinesses){
                    CrmCustomerBusiness cb = new CrmCustomerBusiness();
                    cb.setBusinessId(customerBusiness.getBusinessId());
                    cb.setCid(customerBusiness.getCid());
                    cb.setAddTime(customerBusiness.getAddTime());
                    List<CrmCustomerBusiness> customerBusinessList = crmCustomerBusinessService.selectCrmCustomerBusinessListWithOutGroup(cb);
                    customerBusinessLists.addAll(customerBusinessList);
                }
            }
        }
        int k = 0;
        if(CollectionUtils.isNotEmpty(customerBusinessLists)){
           List<Long> ides =  customerBusinessLists.stream().map(CrmCustomerBusiness::getId).collect(Collectors.toList());
           Long[] idx = ides.stream().toArray(Long[]::new);
           k = crmCustomerBusinessService.deleteCrmCustomerBusinessByIds(idx);
        }
        return toAjax(k);
    }


    @Log(title = "导入用户人数", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, @RequestParam("addTime")String addTime,@RequestParam("dateType")String dateType) throws Exception
    {
        ExcelUtil<CrmCustomerBusiness> util = new ExcelUtil<CrmCustomerBusiness>(CrmCustomerBusiness.class);
        List<CrmCustomerBusiness> customerBusinesses = util.importExcel(file.getInputStream(),1);
        String msg = crmCustomerBusinessService.importData(customerBusinesses,addTime,dateType);
        return AjaxResult.success(msg);
    }

}
